<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<style>
#game {
    width: 1000px;
    height: 700px;
    margin: 50px auto;
}

#game > .mouses {
    width: 100%;
    height: 600px;
    background-color: lightgray;
    
    position: relative;
}

#game > div:nth-child(2) {
    width: 100%;
    height: 100px;
    
    text-align: center;
    line-height: 100px;
}

#game > div:nth-child(2) > button {
    width: 200px;
    height: 50px;
}

#game img {
    width: 60px;
    height: 70px;
    position: absolute;
}

#game .end {
    width: 645px;
    height: 234px;
}
</style>
</head>
<body>
<div id="game">
    <div class="mouses"></div>
    <div>
        <input type="radio" name="level" value="1"> 容易
        <input type="radio" name="level" checked value="2">一般
        <input type="radio" name="level" value="3">难
        <button id="start">开始</button>
    </div>
</div>
<script>
var EASY_LEVEL = 1000;
var NORMAL_LEVEL = 600;
var HARD_LEVEL = 300;

var levelRadio = document.getElementsByName("level");
var startBtn = document.getElementById("start");
var mouses = document.querySelector("#game > .mouses");

startBtn.onclick = function (){
    var level = caculateLevel();  // 计算难度级别
    startBtn.disabled = true;   // 是开始按钮不可用
    mouses.innerHTML = "";  // 情况地鼠区域
    setTimeout(function step(){
        if (determineEnd()) return; // 判断游戏是否结束
        createMouse(mouses);    // 创建地鼠
        setTimeout(step, level);
    }, 0)
}

/**
 * 计算游戏的难度级别
 */
function caculateLevel(){
    // 判断用户的选择难度级别
    var level;  // 记录难度
    for (var r of levelRadio){
        if (r.checked){
            var val = r.value;
            if (val == 1){
                level = EASY_LEVEL;
            }else if (val == 2){
                level = NORMAL_LEVEL;
            }else{
                level = HARD_LEVEL;
            }
        }
    }
    return level;
}

/**
 * 判断游戏是否结束
 */
function determineEnd(){
    // 先判断游戏是否要结束
    if (mouses.childElementCount == 10){
        startBtn.disabled = false;
        mouses.innerHTML = "<img src='./img/end.png' class='end'/>";
        return true;
    }
    return false;
}

/**
 * 创建 mouse并把这个 mouse 添加到指定的容器中
 * @param parentContainer
 */
function createMouse(parentContainer){
    var img = document.createElement("img");
    img.src = "./img/mouse.png";
    img.style.left = randomInt(0, 940) + "px";
    img.style.top = randomInt(0, 530) + "px";
    img.onclick = function (){
//        this.parentNode.removeChild(this);
        img.parentNode.removeChild(img);
    }
    parentContainer.appendChild(img);
}

/**
 作者:李振超      2017年8月1日 16:35
 返回随机的 [from, to] 之间的整数(包括from，也包括to)
 */
function randomInt(from, to){
    return parseInt(Math.random() * (to - from + 1) + from);
}

</script>
</body>
</html>